package com.flyou.ccnucenter.ui.activity.henuBeside.lostFind;

import android.content.Intent;
import android.net.Uri;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.flyou.ccnucenter.R;
import com.flyou.ccnucenter.adapter.LostFoundDetialCommentAdapter;
import com.flyou.ccnucenter.adapter.LostFoundDetialImageGridViewAdapter;
import com.flyou.ccnucenter.domain.Lost;
import com.flyou.ccnucenter.domain.LostComments;
import com.flyou.ccnucenter.domain.MyUser;
import com.flyou.ccnucenter.ui.activity.BaseActivity1;
import com.flyou.ccnucenter.ui.activity.gallery.LostFoundDetialGalleryActivity;
import com.flyou.ccnucenter.utils.BmobErrorCodeUtils;
import com.flyou.ccnucenter.utils.KeyBoardUtils;
import com.flyou.ccnucenter.utils.LoginUtils;
import com.flyou.ccnucenter.utils.MyLog;
import com.flyou.ccnucenter.widget.AutoLoadListView;
import com.flyou.ccnucenter.widget.FousedTextView;
import com.flyou.ccnucenter.widget.NoScrollGridView;
import com.mingle.sweetpick.CustomDelegate;
import com.mingle.sweetpick.Delegate;
import com.mingle.sweetpick.DimEffect;
import com.mingle.sweetpick.SweetSheet;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class LostFoundDetialActivity extends BaseActivity1 implements View.OnClickListener, AutoLoadListView.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    private Button replyToper;
    private AutoLoadListView commentListView;
    private RelativeLayout mTitlebarRlBack;
    private TextView mTitlebarTvTitle;
    private TextView lostFoundTitle, lostFoundTypeName,
            lostFoundCommentNum, lostFoundReadNum, lostFoundReply,
            lostFoundHostName, lostFoundPostTime, lostFoundContent, lostFoundTime;
    private FousedTextView lostfoundAddress;
    private SimpleDraweeView lostFounderHeadimage;
    private View mHeadView;
    private Lost lostFound;
    private String lostfoundId;
    private String lostFounderId;

    private NoScrollGridView gridView;
    private ArrayList<String> photoList;

    private LostFoundDetialCommentAdapter commentAdapter;
    private List<LostComments> commentsList;

    private SwipeRefreshLayout swipe_Reflash;
    private SweetSheet mSweetSheet;
    private EditText responeContent;
    private ImageView responeClose;
    private TextView responeSubmit;
    private RelativeLayout rl;
    private int currentPage = 0;
    private int currentLostConmmentNum = 0;
    private String replyPeople = "";

    @Override
    protected void initView() {
        setContentView(R.layout.activity_lost_found_detial);
        rl = (RelativeLayout) findViewById(R.id.rl);

        swipe_Reflash = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        swipe_Reflash.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

        mTitlebarRlBack = (RelativeLayout) findViewById(R.id.titlebar_rl_back);
        mTitlebarTvTitle = (TextView) findViewById(R.id.titlebar_tv_title);
        replyToper = (Button) findViewById(R.id.lostfound_detial_respone_toper);
        commentListView = (AutoLoadListView) findViewById(R.id.commentListView);
        commentListView.setLoadMoreListener(this);


        mHeadView = View.inflate(LostFoundDetialActivity.this, R.layout.view_lostvound_detail_headview, null);
        lostFoundTitle = (TextView) mHeadView.findViewById(R.id.tv_lostfound_detial_title);
        lostFoundTypeName = (TextView) mHeadView.findViewById(R.id.tv_lostfound_detial_type_name);
        lostFoundCommentNum = (TextView) mHeadView.findViewById(R.id.tv_lostfound_detial_comment_num);
        lostFoundReadNum = (TextView) mHeadView.findViewById(R.id.tv_lostfound_detial_read_num);
        lostFoundHostName = (TextView) mHeadView.findViewById(R.id.tv_lostfound_detial_host_name);
        lostFoundReply = (TextView) mHeadView.findViewById(R.id.tv_lostfound_detial_reply);

        lostFoundPostTime = (TextView) mHeadView.findViewById(R.id.tv_lostfound_post_time);

        lostFoundTime = (TextView) mHeadView.findViewById(R.id.lostFound_time);
        lostFoundContent = (TextView) mHeadView.findViewById(R.id.tv_detial_ccontent);
        lostfoundAddress = (FousedTextView) mHeadView.findViewById(R.id.tv_lostfound_address);
        lostFounderHeadimage = (SimpleDraweeView) mHeadView.findViewById(R.id.tv_lostFound_detial_headimage);
        gridView = (NoScrollGridView) mHeadView.findViewById(R.id.gv_lostfound_post_detial_image);
        commentListView.addHeaderView(mHeadView);
        setupCustomView();

    }

    @Override
    protected void initDate() {

        lostFound = (Lost) getIntent().getSerializableExtra("lostFound");
        lostFoundTitle.setText(lostFound.getTitle());
        setLostFoundType();
        lostFoundReadNum.setText(lostFound.getReadNum() + "");
        lostFoundPostTime.setText(lostFound.getCreatedAt());
        lostFoundTime.setText(lostFound.getLostTime());
        lostFoundContent.setText(lostFound.getDesc());
        lostfoundAddress.setText(lostFound.getAddress());
        lostfoundId = lostFound.getObjectId();
        lostFounderId = lostFound.getUserId();
        if (lostFound.isLost()) {
            mTitlebarTvTitle.setText("失物详情");
        } else {
            mTitlebarTvTitle.setText("招领详情");
        }
        String[] imageUrls = lostFound.getImageUrls();
        if (null == imageUrls) {
            gridView.setVisibility(View.GONE);
        } else {
            if (imageUrls.length > 0) {
                gridView.setVisibility(View.VISIBLE);
                photoList = new ArrayList<>();
                for (int i = 0; i < imageUrls.length; i++) {
                    photoList.add(imageUrls[i]);
                }
                LostFoundDetialImageGridViewAdapter imageGridViewAdapter = new LostFoundDetialImageGridViewAdapter(LostFoundDetialActivity.this, photoList);
                gridView.setAdapter(imageGridViewAdapter);
                gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent galleryIntent = new Intent(LostFoundDetialActivity.this, LostFoundDetialGalleryActivity.class);
                        galleryIntent.putExtra("position", position);
                        galleryIntent.putStringArrayListExtra("photolist", photoList);
                        startActivity(galleryIntent);

                    }
                });

            }
        }

       /*
       * 获取评论总数
       * */
        getLostCommentNum();
        /*
        * 获取用户数据
        * */
        getLostFoundDetial();

        /*
        * 获取评论信息
        * */
        getLostFoundComments();

          /*
        * 更新阅读量
        * */
        upDateReadNum();
    }


    @Override
    protected void setListener() {
        mTitlebarRlBack.setOnClickListener(this);
        replyToper.setOnClickListener(this);
        lostFoundReply.setOnClickListener(this);
        swipe_Reflash.setOnRefreshListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.titlebar_rl_back:
                finish();
                break;
            case R.id.tv_lostfound_detial_reply:
                popReplyDialog("楼主");
                break;
            case R.id.lostfound_detial_respone_toper:
                popReplyDialog("楼主");
                break;

            case R.id.bbs_respone_close:
                if (mSweetSheet.isShow()) {
                    mSweetSheet.dismiss();
                }
                break;
            case R.id.bbs_respone_submit:
                addLostFoundComments();
                break;
        }
    }

    /*
   * 设置物品类型
   * */
    private void setLostFoundType() {
        switch (lostFound.getType()) {
            case 0:
                lostFoundTypeName.setText("书籍");
                break;

            case 1:
                lostFoundTypeName.setText("书包");
                break;

            case 2:
                lostFoundTypeName.setText("证件");
                break;

            case 3:
                lostFoundTypeName.setText("数码");
                break;
            case 4:
                lostFoundTypeName.setText("其他");
                break;

        }
    }

    /*
    * 获取用户数据
    * */
    private void getLostFoundDetial() {
        BmobQuery<MyUser> query = new BmobQuery<MyUser>();
        query.getObject(this, lostFounderId, new GetListener<MyUser>() {

            @Override
            public void onSuccess(MyUser object) {
                String headImage = object.getHeadImage();
                if (!TextUtils.isEmpty(headImage)) {
                    lostFounderHeadimage.setImageURI(Uri.parse(headImage));
                }
                lostFoundHostName.setText(object.getUsername());


            }

            @Override
            public void onFailure(int code, String arg0) {
                Toast.makeText(LostFoundDetialActivity.this, BmobErrorCodeUtils.getMessage(code, arg0), Toast.LENGTH_SHORT).show();
            }

        });

    }

    /*
    * 发布评论
    * */
    public void addLostFoundComments() {
        final String content = responeContent.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(LostFoundDetialActivity.this, "小伙伴，回复内容不能为空哦!", Toast.LENGTH_SHORT).show();
            return;
        }
        MyUser myUser = BmobUser.getCurrentUser(this, MyUser.class);
        LostComments lostComments = new LostComments();
        lostComments.setMyUser(myUser);
        lostComments.setLostFounder(lostFound);
        lostComments.setComment(replyPeople + content);

        lostComments.save(this, new SaveListener() {

            @Override
            public void onSuccess() {
                LostComments newLostComment = new LostComments(BmobUser.getCurrentUser(LostFoundDetialActivity.this, MyUser.class), lostFound, replyPeople + content);

                commentAdapter.addItem(newLostComment);

                Toast.makeText(LostFoundDetialActivity.this, "评论成功", Toast.LENGTH_SHORT).show();
                responeContent.setText("");
                lostFoundCommentNum.setText((currentLostConmmentNum + 1) + "");

            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(LostFoundDetialActivity.this, BmobErrorCodeUtils.getMessage(code, msg), Toast.LENGTH_SHORT).show();
            }
        });
        if (mSweetSheet.isShow()) {
            mSweetSheet.dismiss();
        }
        KeyBoardUtils.closeKeybord(responeContent, LostFoundDetialActivity.this);
    }

    /*
    * 获取失物招领评论
    * */
    private void getLostFoundComments() {

        BmobQuery<LostComments> query = new BmobQuery<LostComments>();
        Lost lost = new Lost();
        lost.setObjectId(lostFound.getObjectId());
        query.addWhereEqualTo("lostFounder", new BmobPointer(lost));
        query.setLimit(10);
        query.setSkip(currentPage * 10);
        query.order("createdAt");
        query.include("myUser");// 希望在查询帖子信息的同时也把发布人的信息查询出来
        query.findObjects(this, new FindListener<LostComments>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                commentListView.setLoadComplete();
                if (swipe_Reflash.isRefreshing()) {
                    swipe_Reflash.setRefreshing(false);
                }
                super.onFinish();
            }

            @Override
            public void onSuccess(final List<LostComments> object) {

                if (null == object || object.size() == 0) {
                }
                if (currentPage == 0) {
                    commentsList = object;
                    commentAdapter = new LostFoundDetialCommentAdapter(LostFoundDetialActivity.this, commentsList, new LostFoundDetialCommentAdapter.OnReplyItemClickListener() {
                        @Override
                        public void onReplyItemClick(int positoion) {
                            List<LostComments> adapterCommentList = commentAdapter.getAllData();
                            popReplyDialog(adapterCommentList.get(positoion).getMyUser().getUsername());
                        }
                    });
                    commentListView.setAdapter(commentAdapter);

                } else {

                    commentAdapter.addAll(object);

                }
            }

            @Override
            public void onError(int code, String msg) {
                Toast.makeText(LostFoundDetialActivity.this, BmobErrorCodeUtils.getMessage(code, msg), Toast.LENGTH_SHORT).show();

            }
        });
    }


    /*
   * 初始化回复弹窗
   * */
    private void setupCustomView() {


        mSweetSheet = new SweetSheet(rl);
        CustomDelegate customDelegate = new CustomDelegate(true,
                CustomDelegate.AnimationType.AlphaAnimation);
        View view = LayoutInflater.from(this).inflate(R.layout.view_bbs_respone_pop, null, false);
        customDelegate.setCustomView(view);
        mSweetSheet.setDelegate(customDelegate);
        mSweetSheet.setBackgroundClickEnable(true);
        mSweetSheet.setBackgroundEffect(new DimEffect(40));
        responeClose = (ImageView) view.findViewById(R.id.bbs_respone_close);
        responeSubmit = (TextView) view.findViewById(R.id.bbs_respone_submit);
        responeContent = (EditText) view.findViewById(R.id.bbs_respone_content);
        responeClose.setOnClickListener(this);
        responeSubmit.setOnClickListener(this);
        mSweetSheet.setBgListener(new Delegate.BgListener() {
            @Override
            public void onClick() {
                if (mSweetSheet.isShow()) {
                    mSweetSheet.dismiss();
                }
            }
        });
    }


    @Override
    public void onBackPressed() {
        if (mSweetSheet.isShow()) {
            mSweetSheet.dismiss();
        } else {

            super.onBackPressed();
        }
    }

    /*
    * 弹出回复按钮
    * */
    private void popReplyDialog(String replayName) {
        if (!LoginUtils.isLogined(LostFoundDetialActivity.this)) {
            LoginUtils.Login(LostFoundDetialActivity.this);
        }
        mSweetSheet.toggle();
        responeContent.setHint("回复 " + replayName + ":");
        if (replayName.equals("楼主")) {
            replyPeople = "";
        } else {
            replyPeople = "回复：{" + replayName + "} ";
        }
    }

    /*
    * 刷新数据
    * */
    @Override
    public void onRefresh() {
        currentPage = 0;
        getLostFoundComments();

    }

    /*
  * 获取更多评论
  * */
    @Override
    public void LoadMore() {
        currentPage++;
        getLostFoundComments();
    }

    /*
    * 更新浏览量
    * */
    public void upDateReadNum() {
        // TODO: 2016/1/15 阅读量更新，你懂得
        Lost updateLost = new Lost();
        updateLost.setReadNum(lostFound.getReadNum() + 3);
        updateLost.setType(lostFound.getType());
        updateLost.update(this, lostFound.getObjectId(), new UpdateListener() {

            @Override
            public void onSuccess() {
                MyLog.d("Lost:upDateReadNum", "success");
            }

            @Override
            public void onFailure(int code, String msg) {
                MyLog.d("Lost:upDateReadNum", BmobErrorCodeUtils.getMessage(code, msg));
            }
        });
    }

    /*
    * 获取评论数量
    * */
    public void getLostCommentNum() {
        BmobQuery<LostComments> query = new BmobQuery<LostComments>();
        Lost lost = new Lost();
        lost.setObjectId(lostFound.getObjectId());
        query.addWhereEqualTo("lostFounder", new BmobPointer(lost));
        query.findObjects(LostFoundDetialActivity.this, new FindListener<LostComments>() {
            @Override
            public void onSuccess(List<LostComments> list) {
                if (null != list) {
                    currentLostConmmentNum = list.size();
                    lostFoundCommentNum.setText(list.size() + "");
                }
            }

            @Override
            public void onError(int i, String s) {

            }
        });
    }
}
